import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'
import { RiskControlNewBaseClass } from '../baseClass'
import { RiskStoreService } from '../risk-store.service'
import { IFormItem, FormItemType } from '@shared/interfaces/common'
import { ISearchOption } from '@shared/interfaces/search'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import {
  riskControlSchemeCodeLength,
  riskControlSchemeCodeReg,
  riskControlSchemeNameLength,
  riskControlSchemeRemarkLength,
} from 'app/utils/contraints'
import { RiskControlScheme } from '@shared/interfaces/risk-control'
import { makeAllControlDirty } from 'app/utils/helpers'
import { I18NService } from '@core'
import { SettingsService } from '@delon/theme'
import { User } from '@shared/interfaces/user'
import { EUserType } from '@shared/enums'
@Component({
  selector: 'app-risk-new-tab-base',
  templateUrl: './tab-base.component.html',
})
export class RiskNewTabBaseComponent extends RiskControlNewBaseClass implements OnInit {
  riskTypeOptions: ISearchOption[] = [
    { label: this.trans('RISK_CTRL_CATEGORY.NORMAL'), value: 'normal' },
    { label: this.trans('RISK_CTRL_CATEGORY.SPECIAL'), value: 'special' },
  ]
  formItems: IFormItem[] = []
  formItemType = FormItemType
  @ViewChild('aams') aams: TemplateRef<void>
  selectedAcquirer: IAamsItem
  isAcquirerUser: boolean
  constructor(
    public settings: SettingsService,
    public riskStore: RiskStoreService,
    public fb: FormBuilder,
    private msg: NzMessageService,
    private i18n: I18NService,
  ) {
    super(fb, riskStore)
  }

  ngOnInit() {
    this.formItems = this.initFormItems()
    this.initAcquirer()
    this.validateForm = this.initValidateForm()
  }

  initAcquirer(): void {
    const authUser = this.settings.user as User
    const disabled = (
      authUser.userType === EUserType.Agent ||
      authUser.userType === EUserType.Merchant ||
      authUser.userType === EUserType.Store  ||
      authUser.userType === EUserType.Institution
    )
    if (disabled) {
      this.selectedAcquirer = {
        code: authUser.insCode,
        name: authUser.insName,
        nameEN: authUser.insNameEN
      }
    }
    this.isAcquirerUser = disabled
  }

  initFormItems(): IFormItem[] {
    return [
      {
        label: this.trans('RISK_CTRL.SCHEME_CODE'),
        errTips: {
          maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeCodeLength }),
          pattern: this.trans('VALIDATION.PATTERN.ALPHANUMERIC_ONLY'),
        },
        formControlName: 'schemeCode',
      },
      {
        label: this.trans('RISK_CTRL.SCHEME_NAME'),
        errTips: {
          required: this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_NAME') }),
          maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeNameLength }),
        },
        formControlName: 'schemeName',
      },
      {
        label: this.trans('RISK_CTRL.SCHEME_DESC'),
        errTips: {
          required: this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_DESC') }),
          maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeRemarkLength }),
        },
        formControlName: 'remark',
      },
      {
        label: this.trans('RISK_CTRL.CATEGORY'),
        errTips: {
          required: this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('RISK_CTRL.CATEGORY') }),
        },
        formControlName: 'category',
        type: FormItemType.SELECT,
        multiple: 'default',
        allowClear: true,
        options: this.riskTypeOptions,
        compareFn: (o1, o2) => o1 === o2,
      },
      {
        label: this.trans('ROLE.OWNER_INSTITUTION'),
        errTips: {
          required: this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('ROLE.OWNER_INSTITUTION') }),
        },
        formControlName: 'insCode',
        type: FormItemType.TEMPLATE,
        template: this.aams,
      },
    ]
  }

  initValidateForm(): FormGroup {
    const { schemeCode, schemeName, remark, category, insCode } = this.riskStore.value
    return this.fb.group({
      schemeCode: [
        schemeCode,
        [Validators.maxLength(riskControlSchemeCodeLength), Validators.pattern(riskControlSchemeCodeReg)],
      ],
      schemeName: [schemeName, [Validators.required, Validators.maxLength(riskControlSchemeNameLength)]],
      remark: [remark, [Validators.required, Validators.maxLength(riskControlSchemeRemarkLength)]],
      category: [category, [Validators.required]],
      insCode: [(insCode || this.selectedAcquirer), [Validators.required]],
    })
  }

  checkValid(): boolean {
    const valid = this.validateForm.valid
    if (valid) {
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    } else {
      makeAllControlDirty(this.validateForm)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    }
    return valid
  }

  pushDataToStore(): void {
    const tmp = this.riskStore.value
    const riskControl: RiskControlScheme = this.validateForm.value
    riskControl.insCode = this.validateForm.value.insCode.code
    Object.assign(tmp, riskControl)
    this.riskStore.setValue(tmp)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
